package com.yhd.task.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yhd.task.dynamic.DynamicCreateTask;
import com.yhd.task.dynamic.SpringContainerExtend;
import com.yhd.task.mapper.TaskMapper;
import com.yhd.task.model.Task;
import com.yhd.task.model.TaskVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 任务相关操作
 *
 * @author yinhuidong3@xiaomi.com
 * @since 2021/7/3
 */
@Service
public class TaskService {

    @Resource
    private TaskMapper taskMapper;
    @Resource
    private SpringContainerExtend springContainerExtend;
    @Resource
    private DynamicCreateTask dynamicCreateTask;
    // add task
    public void addTask(TaskVO taskVO){
        dynamicCreateTask.createTask(taskVO);
        taskMapper.insert(toTask(taskVO));
    }
    //delete task
    public void deleteTask(Integer id){
        stopTask(id);
        taskMapper.deleteById(id);
    }
    //update task
    public void updateTask(TaskVO taskVO){

        taskMapper.updateById(toTask(taskVO));
    }
    //list task page
    public IPage<Task> pageTask(int cur , int size){
        return taskMapper.selectPage(new Page<>(cur,size),null);
    }
    //start task
    public void startTask(Integer id){
        Task task = taskMapper.selectById(id);
        springContainerExtend.registerBean(task.getBeanName(),task.getClass());
    }
    //stop task
    public void stopTask(Integer id){
        Task task = taskMapper.selectById(id);
        springContainerExtend.removeBean(task.getBeanName());
    }

    //list all
    public List<Task> listAll(){
        return taskMapper.selectList(null);
    }

    private Task toTask(TaskVO taskVO){
        Task task = new Task();
        task.setCron(taskVO.getCron());
        task.setTaskName(taskVO.getTaskName());
        task.setDescription(taskVO.getDescription());
        task.setPath(taskVO.getPath());
        task.setLockAtLeastForString(taskVO.getLockAtLeastForString());
        task.setLockAtMostForString(taskVO.getLockAtMostForString());
        task.setLockName(taskVO.getLockName());
        task.setBeanName(taskVO.getBeanName());
        task.setClassName(taskVO.getClassName());
        return task;
    }
}
